import React, { useEffect, useState } from 'react';
import { Card, Table, Button, DialogPlugin, MessagePlugin, Input, Select, Tag } from 'tdesign-react';
import { AddIcon, EditIcon, DeleteIcon, RefreshIcon } from 'tdesign-icons-react';
import { JupiterConfig } from '../../types/configTypes';
import { formatTime } from '../../utils/timeutil';
import {
  fetchConfigList,
  createConfig,
  updateConfig,
  deleteConfig,
  updateConfigStatus,
  refreshConfigCache,
} from '../../services/configService';
import ConfigForm from './components/ConfigForm';

const { Option } = Select;

export default function ConfigPage() {
  const [configList, setConfigList] = useState<JupiterConfig[]>([]);
  const [loading, setLoading] = useState(false);
  const [formVisible, setFormVisible] = useState(false);
  const [editingConfig, setEditingConfig] = useState<Partial<JupiterConfig>>();
  const [title, setTitle] = useState('新增配置');
  const [searchKey, setSearchKey] = useState('');
  const [searchName, setSearchName] = useState('');
  const [searchType, setSearchType] = useState<number | undefined>();
  const [searchStatus, setSearchStatus] = useState<number | undefined>();
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0,
  });

  const getList = async () => {
    setLoading(true);
    try {
      const params = {
        configKey: searchKey,
        configName: searchName,
        configType: searchType,
        status: searchStatus,
        page: pagination.current,
        size: pagination.pageSize,
      };
      const res = await fetchConfigList(params);
      setConfigList(res.data.records || []);
      setPagination(prev => ({
        ...prev,
        total: res.data.total || 0,
      }));
    } finally {
      setLoading(false);
    }
  };

  const handleCreate = () => {
    setEditingConfig(undefined);
    setTitle('新增配置');
    setFormVisible(true);
  };

  const handleEdit = (record: JupiterConfig) => {
    setEditingConfig(record);
    setTitle('编辑配置');
    setFormVisible(true);
  };


  const handleDelete = (record: JupiterConfig) => {
    const confirmDialog = DialogPlugin.confirm({
      header: '删除确认',
      body: `确定删除配置【${record.configName}】？`,
      closeOnOverlayClick: false,
      onConfirm: async () => {
        await deleteConfig(record.uuid);
        MessagePlugin.success('删除成功');
        getList();
        confirmDialog.hide();
      },
      onCancel: () => {
        confirmDialog.hide();
      },
      onClose: () => {
        confirmDialog.hide();
      },
    });
  };

  const handleSubmit = async (data: Partial<JupiterConfig>) => {
    if (editingConfig?.uuid) {
      await updateConfig(editingConfig.uuid, data);
      MessagePlugin.success('更新成功');
    } else {
      await createConfig(data);
      MessagePlugin.success('创建成功');
    }
    setFormVisible(false);
    getList();
  };

  const handleRefreshCache = async () => {
    try {
      await refreshConfigCache();
      MessagePlugin.success('配置缓存刷新成功');
    } catch (error) {
      MessagePlugin.error('配置缓存刷新失败');
    }
  };

  const getTypeText = (type: number) => {
    switch (type) {
      case 1:
        return '字符串';
      case 2:
        return '数字';
      case 3:
        return '布尔值';
      case 4:
        return 'JSON';
      default:
        return '未知';
    }
  };

  const getTypeColor = (type: number) => {
    switch (type) {
      case 1:
        return 'primary';
      case 2:
        return 'success';
      case 3:
        return 'warning';
      case 4:
        return 'danger';
      default:
        return 'default';
    }
  };

  useEffect(() => {
    getList();
  }, [pagination.current, pagination.pageSize, searchKey, searchName, searchType, searchStatus]);

  return (
    <Card title="系统配置管理">
      <div style={{ marginBottom: 16 }}>
        <div style={{ display: 'flex', gap: 16, marginBottom: 16 }}>
          {/* <Input
            placeholder="搜索配置键"
            value={searchKey}
            onChange={(value) => setSearchKey(value)}
            onEnter={() => getList()}
            style={{ width: 150 }}
          /> */}
          <Input
            placeholder="搜索配置名称"
            value={searchName}
            onChange={(value) => setSearchName(value)}
            onEnter={() => getList()}
            style={{ width: 150 }}
          />
          {/* <Select
            placeholder="选择类型"
            value={searchType}
            onChange={(value) => setSearchType(value as number)}
            clearable
            style={{ width: 120 }}
          >
            <Option value={1} label="字符串">
              字符串
            </Option>
            <Option value={2} label="数字">
              数字
            </Option>
            <Option value={3} label="布尔值">
              布尔值
            </Option>
            <Option value={4} label="JSON">
              JSON
            </Option>
          </Select> */}
          <Select
            placeholder="选择状态"
            value={searchStatus}
            onChange={(value) => setSearchStatus(value as number)}
            clearable
            style={{ width: 120 }}
          >
            <Option value={1} label="启用">
              启用
            </Option>
            <Option value={0} label="禁用">
              禁用
            </Option>
          </Select>
          <Button theme="primary" onClick={handleCreate}>
            新增配置
          </Button>
          <Button theme="default" icon={<RefreshIcon />} onClick={handleRefreshCache}>
            刷新缓存
          </Button>
        </div>
      </div>

      <Table
        data={configList}
        rowKey="uuid"
        loading={loading}
        pagination={{
          current: pagination.current,
          pageSize: pagination.pageSize,
          total: pagination.total,
          showJumper: true,
          onChange: (pageInfo) => {
            setPagination(prev => ({
              ...prev,
              current: pageInfo.current,
              pageSize: pageInfo.pageSize,
            }));
          },
        }}
        columns={[
          // {
          //   colKey: 'configKey',
          //   title: '配置键',
          //   width: 200,
          // },
          {
            colKey: 'configName',
            title: '配置名称',
            width: 150,
          },
          {
            colKey: 'configValue',
            title: '配置值',
            width: 300,
            cell: ({ row }) => (
              <div style={{ maxWidth: 300, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
                {row.configValue}
              </div>
            ),
          },
          // {
          //   colKey: 'configType',
          //   title: '类型',
          //   width: 100,
          //   cell: ({ row }) => (
          //     <Tag theme={getTypeColor(row.configType) as any}>
          //       {getTypeText(row.configType)}
          //     </Tag>
          //   ),
          // },
          // {
          //   colKey: 'status',
          //   title: '状态',
          //   width: 100,
          //   cell: ({ row }) => (
          //     <Tag theme={row.status === 1 ? 'success' : 'warning'}>
          //       {row.status === 1 ? '启用' : '禁用'}
          //     </Tag>
          //   ),
          // },
          {
            colKey: 'description',
            title: '描述',
            width: 200,
            cell: ({ row }) => (
              <div style={{ maxWidth: 200, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
                {row.description || '-'}
              </div>
            ),
          },
          {
            colKey: 'updateTime',
            title: '更新时间',
            width: 180,
            cell: ({ row }) => formatTime(row.createTime || ""),
          },
          {
            colKey: 'operation',
            title: '操作',
            width: 150,
            cell: ({ row }) => (
              <>
                <Button
                  theme="primary"
                  variant="text"
                  icon={<EditIcon />}
                  onClick={() => handleEdit(row)}
                >
                  编辑
                </Button>
                <Button
                  theme="danger"
                  variant="text"
                  icon={<DeleteIcon />}
                  onClick={() => handleDelete(row)}
                >
                  删除
                </Button>
              </>
            ),
          },
        ]}
      />

      <ConfigForm
        visible={formVisible}
        onClose={() => setFormVisible(false)}
        onSubmit={handleSubmit}
        initialData={editingConfig}
        title={title}
      />
    </Card>
  );
} 